package com.yami.shop.sys.common.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.event.RegisterRongEvent;
import com.yami.shop.common.config.Constant;
import com.yami.shop.sys.common.dao.SysUserMapper;
import com.yami.shop.sys.common.dao.SysUserRoleMapper;
import com.yami.shop.sys.common.model.SysUser;
import com.yami.shop.sys.common.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * 系统用户
 * @author lgh
 */
@Service("sysUserService")
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserRoleMapper sysUserRoleMapper;

    private final SysUserMapper sysUserMapper;
    
    private final ApplicationContext applicationContext;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAndUserRole(SysUser user) {
        user.setCreateTime(new Date());
        sysUserMapper.insert(user);

        RegisterRongEvent rongEvent = RegisterRongEvent.builder()
                .id("plat_" + user.getUserId()).name(user.getNickName()).portrait("/2022/12/123.png")
                .build();
//        applicationContext.publishEvent(rongEvent);
        
        if(CollUtil.isEmpty(user.getRoleIdList())){
            return;
        }
        //保存用户与角色关系
        sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserAndUserRole(SysUser user) {
        // 超级管理员的用户名不做修改
        if (user.getUserId() == Constant.SUPER_ADMIN_ID) {
            user.setUsername(null);
        }
        // 更新用户
        sysUserMapper.updateById(user);

        //先删除用户与角色关系
        sysUserRoleMapper.deleteByUserId(user.getUserId());

        if(CollUtil.isEmpty(user.getRoleIdList())){
            return ;
        }
        //保存用户与角色关系
        sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void updatePasswordByUserId(Long userId, String newPassword) {
        SysUser user = new SysUser();
        user.setPassword(newPassword);
        user.setUserId(userId);
        sysUserMapper.updateById(user);
    }

    @Override
    public SysUser getByUserName(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public SysUser getSysUserById(Long userId) {
        return sysUserMapper.selectById(userId);
    }
}
